#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
部署准备脚本
用于部署前的数据库初始化和环境准备
"""

import os
import sqlite3
from datetime import datetime
from werkzeug.security import generate_password_hash

def setup_for_deployment():
    """部署前的环境准备"""
    print("开始部署准备...")
    
    # 1. 重置数据库
    reset_database()
    
    # 2. 创建默认管理员账户
    create_default_admin()
    
    # 3. 检查必要文件
    check_required_files()
    
    print("部署准备完成！")
    print("默认管理员账户: admin / admin123")
    print("请在部署后及时修改管理员密码")

def reset_database():
    """重置数据库"""
    db_path = 'instance/student_forms.db'
    
    # 删除现有数据库文件
    if os.path.exists(db_path):
        os.remove(db_path)
        print(f"✓ 已删除现有数据库文件: {db_path}")
    
    # 确保instance目录存在
    os.makedirs('instance', exist_ok=True)
    
    # 创建新的数据库和表
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    # 创建学员表单表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS student_forms (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            phone TEXT NOT NULL,
            age INTEGER NOT NULL,
            grade INTEGER NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ''')
    
    # 创建管理员表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS admin (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE NOT NULL,
            password_hash TEXT NOT NULL
        )
    ''')
    
    conn.commit()
    conn.close()
    
    print(f"✓ 数据库重置完成: {db_path}")

def create_default_admin():
    """创建默认管理员账户"""
    db_path = 'instance/student_forms.db'
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    # 检查是否已存在管理员
    cursor.execute('SELECT COUNT(*) FROM admin WHERE username = ?', ('admin',))
    if cursor.fetchone()[0] == 0:
        # 创建默认管理员
        password_hash = generate_password_hash('admin123')
        cursor.execute(
            'INSERT INTO admin (username, password_hash) VALUES (?, ?)',
            ('admin', password_hash)
        )
        conn.commit()
        print("✓ 默认管理员账户已创建 (admin/admin123)")
    else:
        print("✓ 管理员账户已存在")
    
    conn.close()

def check_required_files():
    """检查必要文件是否存在"""
    required_files = [
        'app.py',
        'web/index.html',
        'web/code/index.css',
        'web/code/index.js',
        'web/favicon.ico'
    ]
    
    missing_files = []
    for file_path in required_files:
        if not os.path.exists(file_path):
            missing_files.append(file_path)
        else:
            print(f"✓ {file_path}")
    
    if missing_files:
        print("⚠️  缺少以下文件:")
        for file_path in missing_files:
            print(f"   - {file_path}")
        return False
    else:
        print("✓ 所有必要文件都存在")
        return True

if __name__ == '__main__':
    setup_for_deployment()